Skip to content

Conversation

@GrabYourPitchforks
Copy link
Member

Part of the "reduce unsafe" effort across the dotnet org.

A prototype static analysis rule identified SocketAddress as being a good candidate to remove a fixed statement. We can't entirely remove unsafe from the target method because the value passed in is a pointer, but at least we can remove the unsafe code surrounding the buffer access.

@ghost ghost added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions label Mar 19, 2025
@GrabYourPitchforks
Copy link
Member Author

@jkotas @BrennanConroy So this was an interesting little bit of refactoring, but the upshot is:

Don't hide the fact that we fundamentally have to interpret a pointer under the covers, since we need to reinterpret_cast<> the pointer anyway. Embrace this, but keep it simple, and then immediately delegate to safer workhorse routines.

So this means the only unsafe code is this:

return pSockaddr->sa_family switch
{
    ADDRESS_FAMILY.AF_INET => new SocketAddressIPv4(*(SOCKADDR_IN*)pSockaddr),
    ADDRESS_FAMILY.AF_INET6 => new SocketAddressIPv6(*(SOCKADDR_IN6*)pSockaddr),
    _ => null
};

The SOCKADDR_IN* struct definitions are generated by CsWin32 and are safe. (Well, safe enough for our use, since we don't try to be clever with them. The definitions will be even safer once CsWin32 gets support for inline arrays.)

// address is network byte order
// when CsWin32 gets support for inline arrays, remove 'AsReadOnlySpan' call below.
// https://github.com/microsoft/CsWin32/issues/1086
return new IPAddress(_sockaddr.sin6_addr.u.Byte.AsReadOnlySpan()); // TODO: Does scope id matter?
Copy link
Member

@BrennanConroy BrennanConroy Mar 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IPAddress does accept a scopeId, any reason not to just pass it in?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH I don't know. The original code didn't pass it in, and I tried to avoid changing the observable behavior in this PR. (The "TODO" comment is copied from the original code.)

@GrabYourPitchforks GrabYourPitchforks merged commit 8645583 into dotnet:main Mar 25, 2025
27 checks passed
@GrabYourPitchforks GrabYourPitchforks deleted the reduce_unsafe branch March 25, 2025 01:07
@dotnet-policy-service dotnet-policy-service bot added this to the 10.0-preview4 milestone Mar 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions reduce-unsafe

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants